/*
 * @Author: yanjikun
 * @Date: 2021-11-04 17:01:54
 * @LastEditors: yanjikun
 * @LastEditTime: 2022-05-30 14:09:50
 * @Description: file content
 */
import router from '@/router'
import { defineStore } from 'pinia'
import { RouteLocationNormalized } from 'vue-router'
export type IRouteItem = Partial<RouteLocationNormalized> & {
  fullPath: string
  name: string
}
const TabsViewState = {
  tabsList: [] as IRouteItem[],
}
type ITabsViewState = typeof TabsViewState
export const useTabsViewStore = defineStore({
  id: 'tabs-view',
  state: (): ITabsViewState => TabsViewState,
  getters: {},
  actions: {
    /** 初始化标签页 */
    initTabsList(routes: IRouteItem[]) {
      this.tabsList = routes
    },
    /** 添加标签页 */
    addTabsList(route: IRouteItem) {
      const flag = this.tabsList.some((item) => item.fullPath === route.fullPath)
      if (flag) return
      this.tabsList.push(route)
    },
    /**关闭标签页 */
    removeTabsList({ fullPath }: IRouteItem) {
      this.tabsList = this.tabsList.filter((item) => item.fullPath !== fullPath)
    },
    /**关闭左侧标签页 */
    closeLeftTabs(route: IRouteItem) {
      const index = this.tabsList.findIndex((item) => item.fullPath === route.fullPath)
      this.tabsList = this.tabsList.slice(index)
    },
    /**关闭右侧标签页 */
    closeRightTabs(route: IRouteItem) {
      const index = this.tabsList.findIndex((item) => item.fullPath === route.fullPath)
      this.tabsList = this.tabsList.slice(0, index + 1)
    },
    /**关闭其他标签页 */
    closeOtherTabs(route: IRouteItem) {
      this.tabsList = this.tabsList.filter((item) => item.fullPath === route.fullPath)
    },
    /**更新tab标题 */
    updateTabTitle(title: string) {
      const currentRoute = router.currentRoute.value
      console.log(currentRoute)
      const upTarget = this.tabsList.find((item) => item.fullPath === currentRoute.fullPath)
      if (upTarget) {
        upTarget.meta!.title = title
      }
    },
  },
})
